package cn.yunhe.dao.impl;

import cn.yunhe.dao.DistrictDao;
import cn.yunhe.model.District;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/*spring注解*/
@Repository(value = "districtDao")
public class DistrictDaoImpl extends HibernateDaoSupport implements DistrictDao {

    @Autowired
    @Qualifier("sessionFactory")
    public void setSessionFactory111(SessionFactory sessionFactory){
        super.setSessionFactory(sessionFactory);
    }


    @Override
    public boolean insertDistrict(District district) {
        getHibernateTemplate().save(district);
        return false;
    }

    @Override
    public boolean updateDistrict(District district) {
        getHibernateTemplate().update(district);
        return false;
    }

    @Override
    public boolean deleteDistrict(Integer sid) {
        getHibernateTemplate().delete(this.getById(sid));
        return false;
    }

    @Override
    public District getById(Integer sid) {
        District district=getHibernateTemplate().get(District.class,sid);
        return null;
    }

    @Override
    public List<District> searchDistrict(String hql) {
        List<District>districtList=getHibernateTemplate().find(hql);
        return districtList;
    }

    @Override
    public List<District> searchDistrict(final District district) {
        List<District>districtList=getHibernateTemplate().executeFind(new HibernateCallback<List<District>>() {
            @Override
            public List<District> doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria=session.createCriteria(District.class);

                if (district!=null){
                    if (district.getDid()>0){
                        criteria.add(Restrictions.eq("sid",district.getDid()));
                    }
                    if (district.getDname()!=null&&district.getDname().trim().length()>0){
                        criteria.add(Restrictions.like("sname",district.getDname(),MatchMode.ANYWHERE));
                    }
                }

                List<District>districtList1=criteria.list();
                return districtList1;
            }
        });
        return null;
    }
}
